// src/kyc/kyc.controller.ts
import { Controller, Post, Get, UseGuards } from '@nestjs/common';
import { KycService } from '../services/kyc.service';
import { JwtAuthGuard } from 'src/auth/guards/jwt-auth.guard';
import { CurrentUser } from 'src/auth/decorators/current-user.decorator';
import { User } from 'src/users/entities/user.entity';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth } from '@nestjs/swagger';
import { ApiResponseDto } from 'src/common/dto/api-response.dto';
import { KycTokenResponseDto, KycStatusDto, KycInfoDto, KycCheckDto } from '../dto/kyc.dto';
import { AppI18nService } from '../../i18n/i18n.service';
import { CurrentLanguage } from '../../i18n/language.decorator';

@ApiTags('kyc')
@ApiBearerAuth('JWT-auth')
@Controller('kyc')
@UseGuards(JwtAuthGuard)
export class KycController {
    constructor(
        private readonly kycService: KycService,
        private readonly i18nService: AppI18nService
    ) { }

    @Post('create')
    @ApiOperation({
        summary: 'Create KYC applicant',
        description: 'Creates a new KYC applicant in Sumsub for the current user'
    })
    @ApiResponse({
        status: 200,
        description: 'KYC applicant created successfully',
        type: ApiResponseDto<any>
    })
    @ApiResponse({
        status: 401,
        description: 'Unauthorized - Invalid or missing JWT token'
    })
    async createApplicant(
        @CurrentUser() user: User,
        @CurrentLanguage() language: string
    ): Promise<ApiResponseDto<any>> {
        try {
            // 使用更简洁的用户ID格式，避免特殊字符
            const userId = `${user.walletAddress}${user.chainId}`;
            const applicant = await this.kycService.createApplicant(userId);
            const message = this.i18nService.getKycMessage('applicant_created', {}, language);

            return ApiResponseDto.success(applicant, message);
        } catch (error) {
            throw error;
        }
    }

    @Post('token')
    @ApiOperation({
        summary: 'Generate KYC access token',
        description: 'Generates a temporary access token for KYC verification process'
    })
    @ApiResponse({
        status: 200,
        description: 'KYC token generated successfully',
        type: ApiResponseDto<KycTokenResponseDto>
    })
    @ApiResponse({
        status: 401,
        description: 'Unauthorized - Invalid or missing JWT token'
    })
    async generateToken(
        @CurrentUser() user: User,
        @CurrentLanguage() language: string
    ): Promise<ApiResponseDto<KycTokenResponseDto>> {
        // 使用 walletAddress + chainId 作为 Sumsub 的 userId
        const userId = `${user.walletAddress}${user.chainId}`;
        const token = await this.kycService.generateAccessToken(userId);
        const message = this.i18nService.getKycMessage('token_generated', {}, language);

        return ApiResponseDto.success({
            token: token
        }, message);
    }

    @Get('status')
    @ApiOperation({
        summary: 'Get current user KYC status',
        description: 'Retrieves the KYC verification status of the currently authenticated user from Sumsub'
    })
    @ApiResponse({
        status: 200,
        description: 'KYC status retrieved successfully',
        type: ApiResponseDto<KycStatusDto>
    })
    @ApiResponse({
        status: 401,
        description: 'Unauthorized - Invalid or missing JWT token'
    })
    @ApiResponse({
        status: 500,
        description: 'Internal server error - Failed to retrieve KYC status'
    })
    async getKycStatus(
        @CurrentUser() user: User,
        @CurrentLanguage() language: string
    ): Promise<ApiResponseDto<any>> {
        try {
            const userId = `${user.walletAddress}${user.chainId}`;
            const status = await this.kycService.getApplicantStatus(userId);
            const message = this.i18nService.getKycMessage('status_retrieved', {}, language);

            return ApiResponseDto.success(status, message);
        } catch (error) {
            throw error;
        }
    }

    @Get('info')
    @ApiOperation({
        summary: 'Get current user KYC information',
        description: 'Retrieves detailed KYC information of the currently authenticated user from Sumsub'
    })
    @ApiResponse({
        status: 200,
        description: 'KYC information retrieved successfully',
        type: ApiResponseDto<KycInfoDto>
    })
    @ApiResponse({
        status: 401,
        description: 'Unauthorized - Invalid or missing JWT token'
    })
    async getKycInfo(
        @CurrentUser() user: User,
        @CurrentLanguage() language: string
    ): Promise<ApiResponseDto<any>> {
        try {
            const userId = `${user.walletAddress}${user.chainId}`;
            const info = await this.kycService.getApplicantInfo(userId);
            const message = this.i18nService.getKycMessage('info_retrieved', {}, language);

            return ApiResponseDto.success(info, message);
        } catch (error) {
            throw error;
        }
    }

    @Get('checks')
    @ApiOperation({
        summary: 'Get current user KYC checks',
        description: 'Retrieves all KYC checks and verification results for the currently authenticated user'
    })
    @ApiResponse({
        status: 200,
        description: 'KYC checks retrieved successfully',
        type: ApiResponseDto<KycCheckDto[]>
    })
    @ApiResponse({
        status: 401,
        description: 'Unauthorized - Invalid or missing JWT token'
    })
    async getKycChecks(
        @CurrentUser() user: User,
        @CurrentLanguage() language: string
    ): Promise<ApiResponseDto<any>> {
        try {
            const userId = `${user.walletAddress}${user.chainId}`;
            const checks = await this.kycService.getApplicantChecks(userId);
            const message = this.i18nService.getKycMessage('checks_retrieved', {}, language);

            return ApiResponseDto.success(checks, message);
        } catch (error) {
            throw error;
        }
    }
}